package meb

import (
    "context"
    "fmt"
    "github.com/gin-gonic/gin"
    "google.golang.org/api/idtoken"
    "vitepress-serve/internal/common/hgin"
    "vitepress-serve/internal/model"
    "github.com/mosongcc/gotool/gtime"
    "golang.org/x/oauth2"
    "net/http"
    "os"
    "time"
)

// GoogleLoginArgs 定义请求参数结构
type GoogleLoginArgs struct {
    Credential string `json:"credential"`
    UserData   struct {
        Email   string `json:"email"`
        Name    string `json:"name"`
        Picture string `json:"picture"`
    } `json:"userData"`
}

func (ctl *Controller) GoogleLogin(ctx *gin.Context) (err error) {
    var args = hgin.ApiReq[GoogleLoginArgs](ctx)
    
    // 验证 Google ID Token
    payload, err := verifyGoogleIDToken(args.Credential)
    if err != nil {
        return err
    }

    // 先通过 OAuth 记录查找用户
    var oauth model.UserOauth
    if err = ctl.db.Where("chan = ? AND openid = ?", "google", payload.Subject).First(&oauth).Error; err == nil {
        // 找到 OAuth 记录，直接查询用户
        var user model.User
        if err = ctl.db.Where("uid = ?", oauth.Uid).First(&user).Error; err != nil {
            return err
        }
        
        // 更新登录信息
        now := gtime.NowF14()
        if err = ctl.db.Model(&user).Updates(map[string]interface{}{
            "log_time": now,
            "log_ip":   ctx.ClientIP(),
            "mtime":    now,
        }).Error; err != nil {
            return err
        }

        // 更新 OAuth 记录的登录时间
        if err = ctl.db.Model(&oauth).Updates(map[string]interface{}{
            "log_time": now,
            "mtime":    now,
        }).Error; err != nil {
            return err
        }

        // 生成 JWT token 并返回用户信息
        return generateTokenAndResponse(ctx, user)
    }

    // OAuth 记录不存在，创建新用户
    now := gtime.NowF14()
    user := model.User{
        Uid:       "G_" + payload.Subject,
        Avatar:    args.UserData.Picture,
        Nickname:  args.UserData.Name,
        Email:     args.UserData.Email,
        Type:      model.USER_TYPE_USR,
        Sex:       model.SEX_0,
        RegDomain: ctx.Request.Host,
        RegIp:     ctx.ClientIP(),
        LogTime:   now,
        LogIp:     ctx.ClientIP(),
        Ctime:     now,
        Mtime:     now,
    }
    
    if err = ctl.db.Create(&user).Error; err != nil {
        return err
    }

    // 创建 OAuth 记录
    oauth = model.UserOauth{
        ID:      "G_" + payload.Subject,
        Uid:     user.Uid,
        Chan:    "google",
        Appid:   os.Getenv("GOOGLE_CLIENT_ID"),
        Openid:  payload.Subject,
        LogTime: now,
        Ctime:   now,
        Mtime:   now,
    }
    
    if err = ctl.db.Create(&oauth).Error; err != nil {
        return err
    }

    return generateTokenAndResponse(ctx, user)
}

// 生成 Token 并返回用户信息
func generateTokenAndResponse(ctx *gin.Context, user model.User) error {
    token := hgin.Token{
        Uid:  user.Uid,
        Type: string(user.Type),
    }
    jwtToken := hgin.GenToken(token, time.Now().Add(24*time.Hour))
    hgin.SetJwtCookie(ctx, jwtToken, int(24*time.Hour.Seconds()))

    hgin.ApiRes(ctx, gin.H{
        "status": "1",
        "data": gin.H{
            "id":     user.Uid,
            "email":  user.Email,
            "name":   user.Nickname,
            "avatar": user.Avatar,
            "type":   user.Type,
        },
    })
    return nil
}

// verifyGoogleIDToken 验证 Google ID Token
func verifyGoogleIDToken(idToken string) (*idtoken.Payload, error) {
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()
    
    // 设置超时的客户端
    client := &http.Client{
        Timeout: 10 * time.Second,
    }
    ctx = context.WithValue(ctx, oauth2.HTTPClient, client)
    
    payload, err := idtoken.Validate(ctx, idToken, os.Getenv("GOOGLE_CLIENT_ID"))
    if err != nil {
        return nil, fmt.Errorf("验证 Google Token 失败: %w", err)
    }
    return payload, nil
}